package io.github.wslxm.springbootplus2.starter.captcha.util;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CaptchaResourceUtil {

    public static List<String> getFileNamesByClasspathDirectory(String directoryPath) {

        List<String> fileNames = new ArrayList<>();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            // 确保目录路径以斜杠结尾
            if (!directoryPath.endsWith("/")) {
                directoryPath += "/";
            }
            // 使用通配符匹配目录下的所有文件
            Resource[] resources = resolver.getResources("classpath*:" + directoryPath + "*");
            for (Resource resource : resources) {
                if (resource.isReadable() && !resource.getURL().toString().endsWith("/")) {
                    String filename = resource.getFilename();
                    if (filename != null) {
                        fileNames.add(directoryPath + filename);
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to list files in directory: " + directoryPath, e);
        }
        return fileNames;
    }
}
